﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using RazorBridge.Helpers;

namespace RazorBridge.Mvc
{
    public class MvcControllerBase : Controller
    {
        public new ActionResult View(string pluginKey, string viewKey)
        {
            return View(FrameworkUtility.CreateCombinedViewName(pluginKey, viewKey));
        }

        public ActionResult View(object model, string pluginKey, string viewKey)
        {
            return View(FrameworkUtility.CreateCombinedViewName(pluginKey, viewKey), model);
        }

        public PartialViewResult PartialView(string pluginKey, string partialViewKey, object model)
        {
            return PartialView(FrameworkUtility.CreateCombinedViewName(pluginKey, partialViewKey), model);
        }

        public PartialViewResult PartialView(string pluginKey, string partialViewKey)
        {
            return PartialView(FrameworkUtility.CreateCombinedViewName(pluginKey, partialViewKey));
        }
        public string PartialViewToString(string pluginKey, string viewKey, object model)
        {
            this.ViewData.Model = model;
            try
            {
                using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
                {
                    ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(this.ControllerContext, FrameworkUtility.CreateCombinedViewName(pluginKey, viewKey));
                    if (viewResult != null)
                    {
                        ViewContext viewContext = new ViewContext(this.ControllerContext, viewResult.View, this.ViewData, this.TempData, stringWriter);
                        if (viewContext != null)
                        {
                            viewResult.View.Render(viewContext, stringWriter);
                        }
                    }

                    return stringWriter.GetStringBuilder().ToString();
                }
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
        }

    }
}
